/**
 * Created by WEI on 2017/07/05.
 */
contentData = decodeURIComponent(contentData);
contentData = JSON.parse(contentData);
formMetadate = decodeURIComponent(formMetadate);
formMetadate = JSON.parse(formMetadate);
$.fn.datagrid.defaults.loadMsg = '正在处理，请稍待。。。';
$.fn.pagination.defaults.beforePageText = '第';
$.fn.pagination.defaults.afterPageText = '页 共{pages}页';
$.fn.pagination.defaults.displayMsg = '显示{from}到{to},共{total}条记录';
if(typeof(userInfo) != "undefined"){
    userInfo = JSON.parse(userInfo);
}
$(function () {
    var relation = "";
    var flag_select = true;
    var mbmc = formMetadate.MBMC;
    var sjwd = "";
    $("head").append("<title>" + mbmc + "</title>");

    $(".selectpicker").selectpicker({
        noneSelectedText : '请选择'
    });
    $(window).on('load', function() {
        $('.selectpicker').selectpicker('val', '');
        $('.selectpicker').selectpicker('refresh');
    });

    /**  解析表格布局  */
    $(".form-widget-layout-wapper").each(function (i, item) {
        var width = $(item).width();
        var type = $(item).attr("type");
        if (type == "table") {
            var cols = $(item).find("table.from-layout-table").children("colgroup").children("col").length;
            $(item).find("table.from-layout-table").css("tableLayout", "fixed");
            $(item).find("table.from-layout-table").children("colgroup").children("col").width(width / (cols || 1));
            $(item).find("table.from-layout-table").width(width);
        }
    });

    /**  解析图表组件  */
    for (var k in contentData) {
        var falg = false;
        var dataValue = contentData[k];
        var type = dataValue.type;
        var _this = $("#" + k), option = dataValue.OPTION || {}, view_sql = option.sql;
        option.type = type;
        _this.data("sql", view_sql);
        var echartsDiv = _this.find(".echarts-div");
        echartsDiv.wrap("<div class='echarts-box'></div>");
        _this.data("option", option);
        _this.data("dataValue", dataValue);
        _this.attr("type", dataValue.type);
        if (dataValue.type == "web_date")
        {
            sjwd = dataValue.WEB_DATE.defaultSjwd;
            var ins = _this.css("marginTop", "15px").webDateCondition("init", dataValue.WEB_DATE);
            _this.attr({"condition": ""});
        }
        else if (dataValue.type == "button_submit")
        {
            _this.css("marginTop", "15px").css("width", "80%").addClass("control-button").click(submitQuery);
        }
        else if (dataValue.type == "button_back")
        {
            _this.css("marginTop", "15px").css("width", "80%").addClass("control-button").on("click", back);
        }
        else if (dataValue.type == "wbsrk")
        {
            _this.css("marginTop", "15px");
        }
        else if (dataValue.type.indexOf("select") != -1) {
            _this.css("marginTop", "15px");
            initSelect(_this, dataValue, contentData);
        }
        else if (dataValue.type == "datagrid")
        {
            var title = dataValue.TITLE.TEXT;
            var table = $("<table class='custom_datagrid'>");
            echartsDiv.parents(".echarts-box").addClass("table-container");
            echartsDiv.append(table);
            echartsDiv.css("height", "auto");
            table.css({"width": "99%"});
            option.height = dataValue.SIZE.HEIGHT;
            //判断是否下钻
            $.each(option.columns, function (i, row) {
                $.each(row, function (j, col) {
                    if (col.linkId) {
                        col.formatter = function (value, row, index) {
                            value = value || "";
                            var href = "";
                            if (col.linkId.indexOf("http") == 0) {
                                if(col.linkId.indexOf("?")!=-1){
                                    href = col.linkId + "&";
                                }else{
                                    href = col.linkId + "?";
                                }

                            } else {
                                href = "/tjfx/yxpjpz/receiveYxpjView";
                                href += "?BDID=" + col.linkId + "&";
                            }
                            var linkField = col.field + "_LINK";
                            var linkValue = row[linkField] || "";
                            href += col.field + "=" + linkValue + "&";
                            $.each(row, function (k, v) {
                                if (col.field != k) {
                                    href += k + "=" + v + "&";
                                }
                            })
                            href = href.substring(0, href.length - 1);
                            return "<a href='" + href + "' target='_blank' class='link_column'>" + value + "</a>";
                        }
                    }
                });
            });
            var columns = extendDeep(option.columns);
            $.each(columns, function (i, row) {
                $.each(row, function (j, col) {
                    if ("true" == col.frozenColumns) {
                        falg = true;
                        delete option.columns[i][j];
                        col.width = col.width + "px";
                        col.rowspan1 = col.rowspan;
                        delete col.rowspan;
                        option.frozenColumns[i][j] = col;
                    }
                });
            });
            //处理数组中为空元素和宽度信息
            procArry(option, falg);
            table.datagrid($.extend({}, option, {
                fit: false,
                onSelect: function (rowIndex, rowData) {
                    $(this).datagrid("unselectRow", rowIndex);
                },
                rowStyler: function (index, row) {
                    if (index % 2 == 1) {
                        return "background-color:#D7EAFB;";
                    }
                }
            }));

            //增加导出按钮
            var linkbutton = $("<a>");
            linkbutton.attr("view_sql", view_sql);
            linkbutton.attr({exp_title: title});
            linkbutton.css({"float": "right", "marginTop": "5px"});
            linkbutton.linkbutton({
                // iconCls:'icon-search',
                text: "导出excel"
            });
            linkbutton.click(function () {
                var params = getAllConParams();
                var obj = $(this).parents(".h4-title").next("div.table-container").find(".echarts-div").find("table.custom_datagrid");
                var exp_title = $(this).attr("exp_title");
                var sql = $(this).attr("view_sql");
                obj.datagrid("exportExcel", {
                    url: "/tjfx/datagridExport/easyui",
                    sql: encodeURIComponent(sql),
                    title: exp_title,
                    params: JSON.stringify(params)
                });
            });
            _this.find("h4.h4-title").append(linkbutton);
        }
        else if (dataValue.type == "treegrid")
        {
            var title = dataValue.TITLE.TEXT;
            var table = $("<table class='custom_treegrid'>");
            echartsDiv.parents(".echarts-box").addClass("table-container");
            echartsDiv.append(table);
            echartsDiv.css("height", "auto");
            table.css({"width": "99%"});
            option.height = dataValue.SIZE.HEIGHT;
            //判断是否下钻
            $.each(option.columns, function (i, row) {
                $.each(row, function (j, col) {
                    if (col.linkId) {
                        col.formatter = function (value, row, index) {
                            value = value || "";
                            var href = "";
                            if (col.linkId.indexOf("http") == 0) {
                                if(col.linkId.indexOf("?")!=-1){
                                    href = col.linkId + "&";
                                }else{
                                    href = col.linkId + "?";
                                }
                            } else {
                                href = "/tjfx/yxpjpz/receiveYxpjView";
                                href += "?BDID=" + col.linkId + "&";
                            }
                            var linkField = col.field + "_LINK";
                            var linkValue = row[linkField] || "";
                            href += col.field + "=" + linkValue + "&";
                            $.each(row, function (k, v) {
                                if (col.field != k) {
                                    href += k + "=" + v + "&";
                                }
                            })
                            href = href.substring(0, href.length - 1);
                            return "<a href='" + href + "' target='_blank' class='link_column'>" + value + "</a>";
                        }
                    }
                });
            });
            var columns = extendDeep(option.columns);
            $.each(columns, function (i, row) {
                $.each(row, function (j, col) {
                    if ("true" == col.frozenColumns) {
                        falg = true;
                        delete option.columns[i][j];
                        col.width = col.width + "px";
                        col.rowspan1 = col.rowspan;
                        delete col.rowspan;
                        option.frozenColumns[i][j] = col;
                    }
                });
            });
            //处理数组中为空元素和宽度信息
            procArry(option, falg);
            table.treegrid($.extend({}, option, {
                fit: false,
                // onSelect: function (rowIndex, rowData) {
                //     $(this).treegrid("unselectRow", rowIndex);
                // },
                rowStyler: function (row) {
                    // return "background-color:#D7EAFB;";
                    // debugger
                    // if (index % 2 == 1) {
                    // }
                }
            }));

            //增加导出按钮
            var linkbutton = $("<a>");
            linkbutton.attr("view_sql", view_sql);
            linkbutton.attr({exp_title: title});
            linkbutton.css({"float": "right", "marginTop": "5px"});
            linkbutton.linkbutton({
                // iconCls:'icon-search',
                text: "导出excel"
            });
            linkbutton.click(function () {
                debugger
                var params = getAllConParams();
                var obj = $(this).parents(".h4-title").next("div.table-container").find(".echarts-div").find("table.custom_treegrid");
                var exp_title = $(this).attr("exp_title");
                var sql = $(this).attr("view_sql");
                obj.datagrid("exportExcel", {
                    url: "/tjfx/datagridExport/easyui",
                    sql: encodeURIComponent(sql),
                    title: exp_title,
                    params: JSON.stringify(params)
                });
            });
            _this.find("h4.h4-title").append(linkbutton);
        }
        else if (dataValue.type == "normaltable")
        {
            chartTable.init(echartsDiv[0], option, "view").resize();
        }
        else if (dataValue.type == "overviewtable")
        {
            chartTableTop.init(echartsDiv[0], option);
            echartsDiv.parents(".echarts-box").addClass("list-container");
        }
        else if (dataValue.type == "toptable")
        {
            chartTableTop.init(echartsDiv[0], option);
            echartsDiv.parents(".echarts-box").addClass("toptable-container");
        }
        else
        {
            echartsDiv.parents(".echarts-box").addClass("echarts-container");
            //未指定分类的都是echart图
            var echartsInstance = echarts.init(echartsDiv[0]);
            if(typeof(option.linkId) != "undefined"){
                echartsInstance.on('click', function (param) {
                    var params = ConditionManager.getParams();
                    for (var i = 0; i < option.series.length; i++) {
                        params[option.series[i].column] = option.series[i].data[param.dataIndex];
                    }
                    var url = decodeURI(location.search);
                    if (url.indexOf("?") != -1) {
                        var str = url.substr(1);
                        var strs = str.split("&");
                        //遍及存放参数
                        for (var i = 0; i < strs.length; i++) {
                            params[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
                        }
                    }
                    delete params.BDID;
                    var href = "";
                    if (option.linkId.indexOf("http") == 0) {
                        href = option.linkId + "?";
                    } else {
                        href = "/tjfx/yxpjpz/receiveYxpjView";
                        href += "?BDID=" + option.linkId + "&";
                    }
                    $.each(params, function (k, v) {
                        href += k + "=" + v + "&";
                    })
                    href = href.substring(0, href.length - 1);
                    window.open(href, "_blank");
                });
            }
            echartsInstance.setOption(option);
            echartsInstance.resize();
        }
    }
    /**  解析标签页布局  */
    $(".form-widget-layout-wapper").each(function (i, item) {
        var type = $(item).attr("type");
        if (type == "tabs") {
            $(item).css({"margin": "20px auto"});
            $(item).tabs({
                activate: function (e) {
                    //custom_datagrid
                    var current = e.currentTarget;
                    var div = $($(current).attr("href"));
                    div.find(".custom_datagrid").each(function () {
                        $(this).datagrid("resize");
                    });
                    div.find("div[_echarts_instance_]").each(function () {
                        echarts.getInstanceByDom(this).resize();
                    });
                }
            });
        }
    });

    function procArry(option, falg) {
        //删除为空的元素
        $.each(option.columns, function (i, row) {
            for (k = option.columns[i].length - 1; k >= 0; k--) {
                if (typeof(option.columns[i][k]) == "undefined") {
                    option.columns[i].splice(k, 1);
                }
            }
        });
        $.each(option.frozenColumns, function (i, row) {
            for (k = option.frozenColumns[i].length - 1; k >= 0; k--) {
                if (typeof(option.frozenColumns[i][k]) == "undefined") {
                    option.frozenColumns[i].splice(k, 1);
                }
            }
        });
        //判断是否有固定列
        if (falg) {
            $.each(option.columns, function (i, row) {
                $.each(row, function (j, col) {
                    option.columns[i][j].width = option.columns[i][j].width + "px";
                })
            })
        }
    }

    function submitQuery() {
        var isReady = ConditionManager.getStatus();
        if (!isReady) return;
        var params = getAllConParams();
        var queryCharList = queryChar(params);

        /** 批量查询图表并setOption */
        queryChartBySqlList(JSON.stringify(queryCharList), function (result) {
            $.each(result, function (index, item) {
                var rs = JSON.parse(item["result"]);
                if (rs.state == "true") {
                    try {
                        $("#" + item["id"]).chartView("setValue", rs);
                    } catch (e) {
                        console.warn(e);
                    }
                } else {
                    console.warn(rs.faultInfo);
                }
            });
        }, JSON.stringify(params));
        flag_select = false;
    }

    function queryChar(params) {
        var queryCharList = [];
        if(typeof(params.startDate) != "undefined" && params.startDate == ""){
            params.startDate = getyyyyMMdd(new Date(),sjwd);
        }
        if(typeof(params.endDate) != "undefined" && params.endDate == ""){
            params.endDate = getyyyyMMdd(new Date(),sjwd);
        }
        $(".form-widget-control-wapper").each(function (i, item) {
            /** 添加查询失败图片 */
            var id = $(item).attr("id"), type = $(item).attr("type"), sql = $(item).data("sql"),
                option = $(item).data("option"), dataValue = $(item).data("dataValue");
            /** 判断是否为normaltable */
            if (type == "button_submit")
            {
            }
            else if (type == "button_back")
            {
            }
            else if (type == "wbsrk")
            {
            }
            else if (type.indexOf("select") != -1)
            {
            }
            else if (type == "normaltable")
            {
                $(item).find(".echarts-div").data("params", params);
                queryCharList.push({
                    "id": id,
                    "type": "table",
                    "sql": sql,
                    "page": option.page,
                    "minnumber": "0",
                    "maxnumber": option.firstpagesize
                });
            }
            else if (type == "datagrid")
            {
                if (!option.pagination)
                {
                    queryCharList.push({
                        "id": id,
                        "type": type,
                        "sql": encodeURIComponent(sql),
                        "page": option.pagination,
                        "minnumber": "0",
                        "maxnumber": option.pageSize
                    });
                }
                else {
                    $("#" + id).find("table.custom_datagrid").datagrid({
                        url: queryDataGridByPage(),
                        onBeforeLoad: function (param) {
                            var pager = $(this).datagrid("getPager");
                            var pageOpt = pager.pagination("options");
                            var page = pageOpt.pageNumber || 1;
                            var rows = pageOpt.pageSize;
                            param.sql = sql;
                            param.params = {
                                "id": id,
                                "type": type,
                                "sql": encodeURIComponent(sql),
                                "page": option.pagination,
                                "minnumber": ((page - 1) * rows) + "",
                                "maxnumber": (page * rows) + ""
                            };
                            param.params = $.extend(param.params, {}, params);
                            if(typeof(params.startDate) != "undefined" && params.startDate == ""){
                                param.params["startDate"] = getyyyyMMdd(new Date(),sjwd);
                            }else{
                                param.params["startDate"] = params.startDate;
                            }
                            if(typeof(params.endDate) != "undefined" && params.endDate == ""){
                                param.params["endDate"] = getyyyyMMdd(new Date(),sjwd);
                            }else{
                                param.params["endDate"] = params.endDate;
                            }
                            param.params = JSON.stringify(param.params);
                        },
                        loadFilter: function (data) {
                            return data.data ? data.data : data;
                        }
                    });
                }
            }
            else if (type == "treegrid")
            {
                if (!option.pagination)
                {
                    queryCharList.push({
                        "id": id,
                        "type": type,
                        "sql": encodeURIComponent(sql),
                        "page": option.pagination,
                        "minnumber": "0",
                        "maxnumber": option.pageSize
                    });
                }
                else {
                    $("#" + id).find("table.custom_treegrid").treegrid({
                        // url: queryTreeGridByPage(),
                        url: queryDataGridByPage(),
                        onBeforeLoad: function (row, param) {
                            debugger
                            var pager = $(this).treegrid("getPager");
                            var pageOpt = pager.pagination("options");
                            var page = pageOpt.pageNumber || 1;
                            var rows = pageOpt.pageSize;
                            param.sql = sql;
                            param.params = {
                                "id": id,
                                "type": type,
                                "sql": encodeURIComponent(sql),
                                "page": option.pagination,
                                "minnumber": ((page - 1) * rows) + "",
                                "maxnumber": (page * rows) + ""
                            };
                            param.params = $.extend(param.params, {}, params);
                            if(typeof(params.startDate) != "undefined" && params.startDate == ""){
                                param.params["startDate"] = getyyyyMMdd(new Date(),sjwd);
                            }else{
                                param.params["startDate"] = params.startDate;
                            }
                            if(typeof(params.endDate) != "undefined" && params.endDate == ""){
                                param.params["endDate"] = getyyyyMMdd(new Date(),sjwd);
                            }else{
                                param.params["endDate"] = params.endDate;
                            }
                            param.params = JSON.stringify(param.params);
                        },
                        loadFilter: function (data) {
                            return data.data ? data.data : data;
                        }
                    });
                }
            }
            else
            {
                /** 将toptable类型转换为table */
                if (type.indexOf("table") != -1) {
                    type = "table";
                }
                queryCharList.push({
                    "id": id,
                    "type": type,
                    "sql": sql,
                    "page": "false"
                });
            }
        });
        return queryCharList;
    }

    function extendDeep(parent, child) {
        child = child || {};
        for (var i in parent) {
            if (parent.hasOwnProperty(i)) {
                if (typeof parent[i] === "object") {
                    child[i] = (Object.prototype.toString.call(parent[i]) === "[object Array]") ? [] : {};
                    extendDeep(parent[i], child[i]);
                } else {
                    child[i] = parent[i];
                }
            }
        }
        return child;
    }

    /**
     * EasyUI DataGrid根据字段动态合并单元格
     * param tableID 要合并table的id
     * param colList 要合并的列,用逗号分隔(例如："name,department,office");
     * param mainColIndex 要合并的主列索引
     */
    function mergeCellsByField(table, colList, mainColIndex) {
        var ColArray = colList.split(",");
        var tTable = table;
        var TableRowCnts = tTable.datagrid("getRows").length;
        var tmpA;
        var tmpB;
        var PerTxt = "";
        var CurTxt = "";
        var alertStr = "";
        for (var i = 0; i <= TableRowCnts; i++) {
            if (i == TableRowCnts) {
                CurTxt = "";
            }
            else {
                CurTxt = tTable.datagrid("getRows")[i][ColArray[mainColIndex]];
            }
            if (PerTxt == CurTxt) {
                tmpA += 1;
            }
            else {
                tmpB += tmpA;
                for (var j = 0; j < ColArray.length; j++) {
                    tTable.datagrid('mergeCells', {
                        index: i - tmpA,
                        field: ColArray[j],
                        rowspan: tmpA,
                        colspan: null
                    });
                }
                tmpA = 1;
            }
            PerTxt = CurTxt;
        }
    }

    /**
     * 关闭当前浏览器tab页
     */
    function back() {
        window.close();
    }

    function getyyyyMMdd(d,sjwd) {
        var curr_date = d.getDate();
        var curr_month = d.getMonth() + 1;
        var curr_year = d.getFullYear();
        String(curr_month).length < 2 ? (curr_month = "0" + curr_month) : curr_month;
        String(curr_date).length < 2 ? (curr_date = "0" + curr_date) : curr_date;
        var yyyyMMdd = "";
        if("year"==sjwd){
            yyyyMMdd = curr_year;
        }else if("month"==sjwd){
            yyyyMMdd = curr_year + "-" + curr_month;
        }else{
            yyyyMMdd = curr_year + "-" + curr_month + "-" + curr_date;
        }
        return yyyyMMdd;
    }

    /*获取全部选择器的参数*/
    function getAllConParams() {
        var params = ConditionManager.getParams();
        //文本框参数合并
        $(".select-yxpjpz").each(function () {
            var key = $(this).parents("li").attr("id");
            var value = $(this).find(".form-control").val();
            var param = {};
            param[key] = value;
            Object.assign(params,param);
        });
        //下拉框参数合并
        $("div[type='select_select']").each(function () {
            var key = $(this).find("li").attr("id");
            var value = $(this).find(".select option:selected").val();
            var param = {};
            param[key] = value;
            Object.assign(params,param);
        });
        //下拉框参数合并
        $(".wrap-div").each(function () {
            var key = $(this).parents("li").attr("id");
            var value = $(this).find("select.selectpicker").val();
            var param = {};
            param[key] = value;
            Object.assign(params,param);
        });
        var url = decodeURI(location.search);
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            //遍及存放参数
            for (var i = 0; i < strs.length; i++) {
                params[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }
        //判断是否为普通机构
        if (userInfo["WSJGLBDM"].indexOf("R") == -1) {
            params["YLJGDM"] = userInfo.YLJGDM;
        }
        params["XZQHDM"] = userInfo.JGXZQHDM;
        return params;
    }

    function initSelect(_this, dataValue, contentData) {
        if (dataValue.type == "select_xzqh")
        {
            if(dataValue.CONTROL_ID != relation && dataValue.RELATION == "" ){
                relation = dataValue.RELATION;
                _this.select_xzqh("loadData", dataValue, contentData);
            }else if(dataValue.CONTROL_ID != relation && dataValue.RELATION != "" ){
                relation = dataValue.RELATION;
                _this.select_xzqh("loadData", dataValue, contentData);
            }else{
                relation = dataValue.RELATION;
            }
        }
        else if(dataValue.type == "select_jg")
        {
            if(dataValue.CONTROL_ID != relation && dataValue.RELATION == "" ){
                relation = dataValue.RELATION;
                _this.select_jg("loadData", dataValue, contentData);
            }else if(dataValue.CONTROL_ID != relation && dataValue.RELATION != "" ){
                relation = dataValue.RELATION;
                _this.select_jg("loadData", dataValue, contentData);
            }else{
                relation = dataValue.RELATION;
            }
        }
        else
        {
            if(dataValue.CONTROL_ID != relation && dataValue.RELATION == ""){
                relation = dataValue.RELATION;
                _this.select_common("loadData", dataValue, contentData);
            }else if(dataValue.CONTROL_ID != relation && dataValue.RELATION != ""){
                relation = dataValue.RELATION;
                _this.select_common("loadData", dataValue, contentData);
            }else{
                relation = dataValue.RELATION;
            }
        }
    }

    submitQuery();
});